package com.gwl.concurrent.simple;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit; 
import static java.lang.System.out; 

public class SimpleDaemons implements Runnable {

	@Override
	public void run() {
		try {
			while(true) { 
				TimeUnit.MILLISECONDS.sleep(100); 
				out.println(Thread.currentThread() + " " + this); 
			}
		} catch (InterruptedException e) {
			out.print("sleep() inerrupted"); 
		} finally { 
			out.print("finally executed"); 
		} 
	} 
	public static void main(String[] args) throws InterruptedException { 
		ExecutorService exec = Executors.newCachedThreadPool(new ThreadFactory() {
			@Override
			public Thread newThread(Runnable r) { 
				Thread t = new Thread(r); 
				t.setDaemon(true); 
				return t;
			} 
		}); 
		for(int i=0; i<10; i++) { 
			exec.execute(new SimpleDaemons()); 
		} 
		exec.shutdown(); 
		out.println("All daemons started"); 
		TimeUnit.MILLISECONDS.sleep(175); 
	}

}
